package com.matrix.draft.jvm.heap;

/**
 * 死锁测试类
 */
public class TestDeadLock {

    static Object lockA = new Object();
    static Object lockB = new Object();

    public static void main(String[] args) {
        // 线程1
        new Thread(()->{
            synchronized (lockA){
                sleep(1000);
                synchronized (lockB){
                    System.out.println(getTName()+"两个锁全部拿到了!");
                }
            }
        },"ThreadA").start();

        // 线程2
        new Thread(()->{
            sleep(100); // 睡100毫秒来保证ThreadA先拿到A锁
            synchronized (lockB){
                synchronized (lockA){
                    System.out.println(getTName()+"两个锁全部拿到!");
                }
            }
        },"ThreadB").start();
    }

    // 当前线程睡眠
    static void sleep(long millis){
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    // 获取当先线程名
    static String getTName(){
        return Thread.currentThread().getName();
    }
}
